package org.dydl.common.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

/**
 * token验证
 * 
 * @author YM
 *
 */
public class TokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

	private String servletPath;

	private static final String HEADER_SECURITY_TOKEN = "X-AuthToken";
	private final String TOKEN_FILTER_APPLIED = "TOKEN_FILTER_APPLIED";
	// private AuthTokenGeneratorService authTokenGeneratorService;
	// private IAuthTokenService authTokenService;

	protected TokenAuthenticationFilter(RequestMatcher requiresAuthenticationRequestMatcher) {
		super(requiresAuthenticationRequestMatcher);
		// TODO Auto-generated constructor stub
	}

	// public TokenAuthenticationFilter(String servletPath,
	// AuthTokenGeneratorService authTokenGeneratorService,
	// IAuthTokenService authTokenService) {
	//
	// super(servletPath);
	// this.servletPath = servletPath;
	// this.authTokenGeneratorService = authTokenGeneratorService;
	// this.authTokenService = authTokenService;
	//
	// }

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		// HttpServletResponse res = (HttpServletResponse) response;
		RequestMatcher reqMatcher = new AntPathRequestMatcher(servletPath);
		if (reqMatcher.matches(req)) {
			String token = req.getHeader(HEADER_SECURITY_TOKEN);
			AbstractAuthenticationToken userAuthenticationToken = null;
			request.setAttribute(TOKEN_FILTER_APPLIED, Boolean.TRUE);
			userAuthenticationToken = authenticateByToken(token);
			if (userAuthenticationToken == null) {
				// TODO:做测试，先跳过
				// throw new AuthenticationServiceException("Token验证失败！");
			}
			// session过期时间设置为5小时
			req.getSession().setMaxInactiveInterval(5 * 60 * 60);
		}
		chain.doFilter(request, response);
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException, IOException, ServletException {
		return null;

	}

	/**
	 * authenticate the user based on token
	 * 
	 * @return
	 */
	private AbstractAuthenticationToken authenticateByToken(String token) {
		if (null == token) {
			return null;
		}

		AbstractAuthenticationToken authToken = null;

		try {
			// String[] tokens = authTokenGeneratorService.decode(token);
			//
			// AuthToken tokenEntry = (AuthToken)
			// authTokenService.findUserByTokenAndSeries(tokens[0], tokens[1])
			// .getData();
			// if (null == tokenEntry) {
			// return null;
			// }
			//
			// UserContext securityUser = new UserContext(tokenEntry.getUser());
			//
			// authToken = new
			// UsernamePasswordAuthenticationToken(securityUser.getUsername(), "",
			// securityUser.getAuthorities());
		} catch (Exception ex) {
			logger.error("Failed to authenticate user for token" + token + "{ }", ex);
		}

		return authToken;
	}

}
